<template>
  <div :class="[customClass, 'calendar']">
    <div class="title">{{ title }}</div>
    <div class="header">
      <div class="block">日</div>
      <div class="block">一</div>
      <div class="block">二</div>
      <div class="block">三</div>
      <div class="block">四</div>
      <div class="block">五</div>
      <div class="block">六</div>
    </div>

    <div class="body">
      <div
        v-for="num in placeholderEleCount"
        :key="'place_day_' + num"
        class="block"
      />
      <div
        v-for="day in allDays"
        class="block"
        :key="'day_' + day"
        v-html="renderLabel(day)"
      />
    </div>
  </div>
</template>

<script>
// TODO: 待优化
const BIG_MONTH = [1, 3, 5, 7, 8, 10, 12];
const SMALL_MONTH = [4, 6, 9, 11];
function getDaysFromCurrentMonth(year, month) {
  if (BIG_MONTH.indexOf(month) !== -1) {
    return 31;
  }

  if (SMALL_MONTH.indexOf(month) !== -1) {
    return 30;
  }

  if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) {
    return 29;
  }

  return 28;
}

function getWeekdayOfMonth(year, month) {
  const fistDate = new Date(year, month - 1, 1);
  return fistDate.getDay();
}

export default {
  name: "Calendar",
  props: {
    renderLabel: {
      type: Function,
      default: (day) => day,
    },
    customClass: String,
  },
  data() {
    return {
      title: "",
      placeholderEleCount: 0,
      allDays: 0,
    };
  },
  created() {
    this.init();
  },
  mounted() {},
  methods: {
    init() {
      const today = new Date();
      const year = today.getFullYear();
      const month = today.getMonth() + 1;

      const days = getDaysFromCurrentMonth(year, month);
      this.title = `${year}年${month}月`;
      this.allDays = getDaysFromCurrentMonth(year, month);
      this.placeholderEleCount = getWeekdayOfMonth(year, month);
    },
  },
};
</script>

<style lang="less" scoped>
.calendar {
  .header {
    display: flex;
    flex-wrap: nowrap;
    width: 100%;
    height: 32px;
    margin-top: 6px;
    background-color: #f4f7ff;
    line-height: 32px;
  }

  .body {
    display: flex;
    flex-wrap: wrap;
  }

  .block {
    width: 14.28%;
    font-size: 15px;
    color: #333333;
    text-align: center;
  }

  .title {
    width: 100%;
    height: 26px;
    line-height: 26px;
    font-size: 17px;
    font-family: PingFangSC, PingFangSC-Regular;
    font-weight: 400;
    text-align: center;
    margin-top: 35px;
  }
}
</style>



